#!/usr/bin/env python3
"""
Flask MCP Server

面向 python-flask 软件的 MCP Server，提供 Flask 命令行操作的工具。

MCP tools 列表：
1. flask_create_webapp - 创建并启动 Flask web 应用
   - 用途：创建一个简单的 Flask web 应用，启动开发服务器并验证服务
   - 参数：port (int): 服务端口号, host (str): 主机地址, route_path (str): 路由路径, response_text (str): 响应文本
   - 返回：统一的 JSON 结构，包含命令执行结果
"""

import subprocess
import json
import tempfile
import os
from typing import List
from mcp.server.fastmcp import FastMCP, Context

mcp = FastMCP("Flask MCP Server")

@mcp.tool()
def flask_create_webapp(port: int = 5000, host: str = "0.0.0.0", route_path: str = "/", response_text: str = "Hello World") -> dict:
    """
    创建并启动一个简单的 Flask web 应用
    
    参数:
        port: 服务端口号，默认 5000
        host: 主机地址，默认 "0.0.0.0"
        route_path: 路由路径，默认 "/"
        response_text: 响应文本，默认 "Hello World"
    
    返回:
        {
            "success": bool,      # 执行是否成功
            "command": str,       # 执行的命令
            "exit_code": int,     # 退出码
            "stdout": str,        # 标准输出
            "stderr": str         # 标准错误
        }
    """
    try:
        # 创建 Flask 应用文件
        flask_code = f'''#main.py
from flask import Flask
app = Flask(__name__)

@app.route('{route_path}')
def index():
    return '{response_text}'

if __name__ == '__main__':
    app.run(port={port}, host='{host}')
'''
        
        # 写入临时文件
        with tempfile.NamedTemporaryFile(mode='w', suffix='.py', delete=False) as f:
            f.write(flask_code)
            temp_file = f.name
        
        # 启动 Flask 应用
        command = f"python3 {temp_file}"
        result = subprocess.run(
            ["python3", temp_file],
            capture_output=True,
            text=True,
            timeout=30  # 30秒超时
        )
        
        # 清理临时文件
        try:
            os.unlink(temp_file)
        except:
            pass
            
        return {
            "success": result.returncode == 0,
            "command": command,
            "exit_code": result.returncode,
            "stdout": result.stdout,
            "stderr": result.stderr
        }
        
    except subprocess.TimeoutExpired:
        # Flask 服务器通常会持续运行，超时是预期的
        try:
            os.unlink(temp_file)
        except:
            pass
        return {
            "success": True,
            "command": command,
            "exit_code": 0,
            "stdout": "Flask server started successfully (timeout expected for long-running server)",
            "stderr": ""
        }
    except Exception as e:
        return {
            "success": False,
            "command": f"python3 {temp_file}",
            "exit_code": -1,
            "stdout": "",
            "stderr": f"Error: {str(e)}"
        }

if __name__ == "__main__":
    mcp.run()